<template>
  <div class="hospital-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>医院管理</h2>
      <p>管理智慧医疗系统中所有合作医院的信息，包括医院基本信息、联系方式、地址等</p>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-container">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="医院名称:">
          <el-input
            v-model="searchForm.name"
            placeholder="输入标题或关键字"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="医院等级:">
          <el-select
            v-model="searchForm.level"
            placeholder="请选择医院等级"
            clearable
            style="width: 160px"
          >
            <el-option label="三甲" value="三甲" />
            <el-option label="二甲" value="二甲" />
            <el-option label="一甲" value="一甲" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="医院类型:">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择医院类型"
            clearable
            style="width: 160px"
          >
            <el-option label="综合医院" value="综合医院" />
            <el-option label="专科医院" value="专科医院" />
            <el-option label="中医医院" value="中医医院" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <div class="button-group">
            <el-button type="primary" :icon="Search" @click="handleSearch">
              筛选
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">
              重置
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 医院列表 -->
    <div class="card-container" style="overflow-x: auto;">
      <div class="table-header">
        <h3>医院列表</h3>
        <div class="header-actions">
            <el-button type="primary" :icon="Plus" @click="handleAddPage">
              新增医院
            </el-button>
          </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        @selection-change="handleSelectionChange"
        table-layout="fixed"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="name" label="医院名称" min-width="200">
          <template #default="{ row }">
            <div class="name-cell">
              <span class="name-text cursor-pointer" @click="handleView(row)">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="imageUrl" label="列表图" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              class="hospital-thumbnail"
              fit="cover"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="level" label="医院等级" width="100" />
        
        <el-table-column prop="type" label="医院类型" width="120" />
        
        <el-table-column prop="uploader" label="上传人" width="120" />
        
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-space wrap>
              <el-button
                type="primary"
                :icon="View"
                size="small"
                @click="handleView(row)"
              >
                查看详情
              </el-button>
              
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="handleEditPage(row)"
              >
                编辑
              </el-button>
              
              <el-button
                type="danger"
                size="small"
                :loading="deleteLoading && currentDeleteId === row.id"
                @click="handleDelete(row)"
              >
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-operations" v-if="selectedRows.length > 0">
        <span>已选择 {{ selectedRows.length }} 项</span>
        <el-button 
          type="danger" 
          :icon="Delete" 
          :loading="batchDeleteLoading"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹窗功能已移除，新增医院通过页面跳转实现 -->

    <!-- 医院详情功能已迁移到独立页面 -->
    <!-- 对话框代码已删除，详情查看功能通过页面跳转实现 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import { hospitalApi } from '@/api/index'
import type { HospitalItem, HospitalSearchParams } from '@/api/index'

/**
 * 智慧医疗系统 - 医院管理页面
 * 功能：医院信息的增删改查、图片上传、状态管理
 */

// 接口类型定义
interface HospitalItem {
  id: number
  name: string
  imageUrl: string
  level: string
  type: string
  address: string
  phone: string
  description?: string
  isEnabled: boolean
  uploader: string
  uploadTime: string
}

interface SearchForm {
  name: string
  level: string
  type: string
}

// 弹窗相关接口定义已移除

// 响应式数据
const loading = ref(false)
const selectedRows = ref<HospitalItem[]>([])
// 删除相关状态
const deleteLoading = ref(false)
const batchDeleteLoading = ref(false)
const currentDeleteId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  level: '',
  type: ''
})

// 表格数据
const tableData = ref<HospitalItem[]>([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 生命周期
onMounted(() => {
  loadData()
})

// 方法
/**
 * 加载医院数据
 * @param resetPagination 是否重置分页
 */
const loadData = async (resetPagination = false) => {
  if (resetPagination) {
    pagination.currentPage = 1
  }
  
  loading.value = true
  try {
    const params: HospitalSearchParams = {
      name: searchForm.name,
      level: searchForm.level,
      type: searchForm.type,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await hospitalApi.getList(params)
    
    if (response.code === 200) {
      const data = response.data
      tableData.value = data.items
      pagination.total = data.totalCount
    } else {
      ElMessage.error('获取医院数据失败')
    }
  } catch (error) {
    console.error('加载医院数据出错:', error)
    ElMessage.error('加载医院数据失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 查看医院详情
 */
const handleView = (row: HospitalItem) => {
  router.push({ path: `/content/hospital/detail/${row.id}` })
}

/**
 * 删除医院
 */
const handleDelete = async (row: HospitalItem) => {
  ElMessageBox.confirm('确定要删除该医院吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      deleteLoading.value = true
      currentDeleteId.value = row.id
      try {
        const response = await hospitalApi.delete(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadData()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        console.error('删除医院出错:', error)
        ElMessage.error('删除失败，请重试')
      } finally {
        deleteLoading.value = false
        currentDeleteId.value = null
      }
    })
    .catch(() => {
      // 取消删除
    })
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的医院')
    return
  }

  ElMessageBox.confirm('确定要删除选中的医院吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      batchDeleteLoading.value = true
      const ids = selectedRows.value.map(row => row.id)
      try {
        const response = await hospitalApi.batchDelete(ids)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          selectedRows.value = []
          loadData()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        console.error('批量删除医院出错:', error)
        ElMessage.error('删除失败，请重试')
      } finally {
        batchDeleteLoading.value = false
      }
    })
    .catch(() => {
      // 取消删除
    })
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  searchForm.name = ''
  searchForm.level = ''
  searchForm.type = ''
  pagination.currentPage = 1
  loadData()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  loadData()
}

/**
 * 选择行改变
 */
const handleSelectionChange = (rows: HospitalItem[]) => {
  selectedRows.value = rows
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

/**
 * 页面跳转新增医院
 */
const handleAddPage = () => {
  router.push({ path: '/content/hospital/add' })
}

/**
 * 页面跳转编辑医院
 */
const handleEditPage = (row: HospitalItem) => {
  router.push({ path: `/content/hospital/edit/${row.id}` })
}
</script>

<style lang="scss" scoped>
.hospital-management {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .search-container {
    margin-bottom: 24px;
    padding: 16px;
    background-color: $bg-color;
    border-radius: 4px;
  }
  
  .card-container {
    background-color: $bg-color;
    border-radius: 4px;
    padding: 24px;
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
  
  .pagination-container {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
  }
  
  .batch-operations {
    margin-top: 16px;
    padding: 12px;
    background-color: $bg-color;
    border-radius: 4px;
    display: flex;
    align-items: center;
    
    span {
      margin-right: 16px;
    }
  }
  
  .hospital-thumbnail {
    width: 80px;
    height: 45px;
    border-radius: 4px;
  }
  
  .form-container {
    padding: 16px 0;
  }
  
  .upload-container {
    width: 100%;
    
    .uploaded-image {
      width: 100%;
      max-height: 200px;
      object-fit: cover;
      border-radius: 4px;
    }
    
    .upload-placeholder {
      width: 100%;
      height: 120px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px dashed $border-color;
      border-radius: 4px;
      
      .upload-icon {
        font-size: 24px;
        color: $text-color-placeholder;
        margin-bottom: 8px;
      }
      
      .upload-text {
        color: $text-color-placeholder;
      }
    }
    
    .upload-tips {
      margin-top: 8px;
      font-size: 12px;
      color: $text-color-placeholder;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  .hospital-detail {
    padding: 16px;
    
    .detail-row {
      display: flex;
      margin-bottom: 16px;
      
      .detail-label {
        width: 120px;
        text-align: right;
        font-weight: 500;
        margin-right: 16px;
      }
      
      .detail-value {
        flex: 1;
        word-break: break-word;
      }
      
      .detail-image {
        width: 200px;
        height: 115px;
        border-radius: 4px;
        object-fit: cover;
      }
    }
  }
}
</style>